package user_api

import (
	"fmt"
	"gin_study_blog/common"
	"gin_study_blog/common/blog_type"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"gin_study_blog/plugins/log_stash"
	"gin_study_blog/utils"
	"github.com/gin-gonic/gin"
)

type emailLoginRequest struct {
	UserName string `json:"user_name" binding:"required" msg:"请输入邮箱"`
	Password string `json:"password" binding:"required" msg:"请输入密码"`
}

func (UserApi) EmailLoginView(c *gin.Context) {
	var cr emailLoginRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		http.FailWithError(err, &cr, c)
		return
	}

	log := log_stash.NewLogByGin(c)

	// 用户是否存在
	userMoDel := new(models.UserModel)
	err = common.DB.Take(&userMoDel, "user_name = ? OR email = ?", cr.UserName, cr.UserName).Error
	if err != nil {
		common.Log.Error(err)
		log.Waring(fmt.Sprintf("%s 用户不存在", cr.UserName))
		http.FailWithMessage("用户名或密码错误", c)
		return
	}
	// 判断密码
	isCheckPwd := utils.ComparePasswords(userMoDel.Password, cr.Password)
	if !isCheckPwd {
		common.Log.Error(err)
		log.Waring(fmt.Sprintf("用户名或密码错误 %s %s", cr.UserName, cr.Password))
		http.FailWithMessage("用户名或密码错误", c)
		return
	}
	// 登录成功, 生成 token
	token, err := utils.GenUserToken(utils.JwtUser{
		NickName: userMoDel.NickName,
		Role:     int(userMoDel.Role),
		UserID:   userMoDel.ID,
	})
	if err != nil {
		common.Log.Error(err)
		log.Waring(fmt.Sprintf("token 生成失败%s", err.Error()))
		http.FailWithMessage("token 生成失败", c)
		return
	}
	log = log_stash.New(c.ClientIP(), token)
	log.Info("登录成功")

	common.DB.Create(&models.LoginDataModel{
		UserID:    userMoDel.ID,
		IP:        c.ClientIP(),
		NickName:  userMoDel.NickName,
		Token:     token,
		Device:    "",
		Addr:      "内网",
		LoginType: blog_type.LoginTypeEmail,
	})
	http.IsOkWithData(token, c)
}
